package stone926.mods.more_enchantments.items;

import net.minecraft.entity.EntityType;
import net.minecraft.entity.mob.ZombieVillagerEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.predicate.entity.EntityPredicates;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.Hand;
import net.minecraft.util.TypedActionResult;
import net.minecraft.util.math.Box;
import net.minecraft.world.World;
import stone926.mods.more_enchantments.mixins.accessors.ZombieVillagerAccessor;
import stone926.mods.more_enchantments.util.RandomUtil;

import java.util.List;

public class AppleOfRedemptionItem extends Item {

  private final Type type;

  public AppleOfRedemptionItem(Settings settings, Type type) {
    super(settings);
    this.type = type;
  }

  @Override
  public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
    ItemStack stack = user.getStackInHand(hand);
    if (type.equals(Type.RANGE) && !world.isClient) {
      List<ZombieVillagerEntity> entities = world.getEntitiesByType(
        EntityType.ZOMBIE_VILLAGER, Box.from(user.getPos()).expand(RandomUtil.nextInt(5, 10, user.getRandom())),
        EntityPredicates.VALID_LIVING_ENTITY
      );
      if (!entities.isEmpty()) {
        entities.forEach(zv -> ((ZombieVillagerAccessor) zv).invokeFinishConversion((ServerWorld) world));
        stack.damage(1, user, p -> p.sendToolBreakStatus(hand));
        return TypedActionResult.success(stack);
      } else return TypedActionResult.pass(stack);
    } else return TypedActionResult.pass(stack);
  }

  public enum Type {SINGLE, RANGE}

}
